﻿using myBackupService.Common;
using myBackupService.Model;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using TouchSocket.Core;
using TouchSocket.Http;

namespace myBackupService.Backup
{
    public class GetCatalogHttpPlug : PluginBase, IHttpPlugin
    {
        public async Task OnHttpRequest(IHttpSessionClient client, HttpContextEventArgs e)
        {
            if (!e.Context.Request.IsGet()|| !e.Context.Request.UrlEquals("/GetCatalog"))
            {
                await e.InvokeNext();
                return;
            } 
            try
            {
                var pathId = e.Context.Request.Query.Get("pathId");
                var path = e.Context.Request.Query.Get("path");
                var includeFiles=  e.Context.Request.Query.Get("includeFiles");//是否包含文件
                var excludeExtensions= e.Context.Request.Query.Get("excludeExtensions");//要排除的文件扩展名
                var excludeDirectories=   e.Context.Request.Query.Get("excludeDirectories");//要排除的目录名
                var skipHidden=  e.Context.Request.Query.Get("skipHidden");//是否跳过隐藏文件和目录
                var includeDirectories = e.Context.Request.Query.Get("includeDirectories"); //是否包含目录
                var maxDepth = e.Context.Request.Query.Get("maxDepth");//最大递归深度（0表示无限制）

                var options = new DirectoryScanOptions();
                if(!string.IsNullOrEmpty(includeFiles))
                    options.IncludeFiles=Convert.ToBoolean(includeFiles);
                if(!string.IsNullOrEmpty(excludeExtensions))
                    options.ExcludeExtensions = includeFiles.Split(',');
                if (!string.IsNullOrEmpty(excludeDirectories))
                    options.ExcludeDirectories = excludeDirectories.Split(',');
                if (!string.IsNullOrEmpty(skipHidden))
                    options.SkipHidden = Convert.ToBoolean(skipHidden);
                if (!string.IsNullOrEmpty(includeDirectories))
                    options.IncludeDirectories = Convert.ToBoolean(includeDirectories);
                if (!string.IsNullOrEmpty(maxDepth))
                    options.MaxDepth = Convert.ToInt32(maxDepth);
                XElement xElement = new XElement("Root");
                var paths = BackupConfig.Instance.Paths.Select(d=>d.Value);
                if(!string.IsNullOrEmpty(pathId))
                {
                    paths= BackupConfig.Instance.Paths.Where(d => d.Key == pathId).Select(d=>d.Value);
                }
                
                foreach (var item in paths)
                {
                    var directoryPath = item.Path;
                    pathId= PassWordHelper.Md532(directoryPath);
                    if (!string.IsNullOrEmpty(path))
                    {
                        directoryPath = Path.Combine(Directory.GetParent(directoryPath).FullName , path.TrimStart('\\'));
                    }
                    if (!Directory.Exists(directoryPath))
                        continue;
                    var basicXml = DirectoryToXmlGenerator.GenerateXmlFromDirectory(pathId,directoryPath, options);
                    xElement.Add(basicXml);
                }
                await e.Context.Response.SetStatusWithSuccess().FromXml(xElement.ToString()).AnswerAsync();
            }
            catch (Exception ex)
            {
                client.Logger.Exception(ex);
            }
            await e.InvokeNext();
        }
    }
}
